package com.cms.server.resolver.plugins.sctz;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.efounder.builder.base.data.DataSetUtils;
import com.efounder.builder.base.data.EFDataSet;
import com.efounder.builder.base.data.EFRowSet;
import com.efounder.eai.data.JParamObject;
import com.efounder.form.EFFormDataModel;
import com.efounder.form.io.FormDataResolverAdapter;
import com.efounder.form.server.resolver.util.SYS_MDL_VAL;
import com.efounder.sql.JStatement;
import com.metadata.bizmodel.SYS_MODEL;
import com.persistence.FLOW_TASK_LIST;


/**
 * <p>Title: 会签节点的上一个节点选择部门退回</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2014</p>
 * @author prayer
 * @version 1.0
 */
public class CMSCountersignNextNodeRollback extends FormDataResolverAdapter {
	//初始化FormDataModel
	public void finishSaveForm(JStatement stmt, EFFormDataModel model, JParamObject PO) throws Exception {
		EFDataSet                    billDataSet = model.getBillDataSet();
		EFDataSet                    itemDataSet = EFDataSet.getInstance();
		EFRowSet                      itemRowSet = null;
		EFDataSet                     flowNodeDS = null;
		EFRowSet                      flowRowset = EFRowSet.getInstance();
		EFDataSet                      BMDataset = EFDataSet.getInstance(new String[]{"F_BMBH"});
		EFRowSet                        BMRowSet = null;
		String                            strSql = "";
		ResultSet                             rs = null;
		long                             curTime = new Date().getTime();
		String                            F_KJQJ = billDataSet.getRowSet(0).getString(PO.GetValueByParamName(SYS_MODEL._BLFL_KJQJ_COL_, SYS_MDL_VAL.BILL_KJQJ), "");
		String                            F_DJBH = billDataSet.getRowSet(0).getString(PO.GetValueByParamName(SYS_MODEL._BILL_BH_COL_, SYS_MDL_VAL.BILL_BH), null);
		String                           FLOW_ID = PO.GetValueByParamName(FLOW_TASK_LIST._FLOW_ID, "");
		String                           NODE_ID = PO.GetValueByParamName(FLOW_TASK_LIST._OP_NODE, "");
		String                     RESR_IN_CAUSE = PO.GetValueByParamName(FLOW_TASK_LIST._RESR_IN_CAUSE, "");
		EFRowSet                      nodeRowset = EFRowSet.getInstance();
		String                   strHQDataSetKey = "";		//会签节点对应的单据分录数据集KEY
		java.util.List<String>    dataSetKeyList = new java.util.ArrayList<String>();//单据分录数据集KEY
		String                        rollbackBM = "";
		String[]                         bmArray = null;
		Map<String, String>        rollbackBMMap = new HashMap<String, String>();
		
		if(!RESR_IN_CAUSE.equals("rollback")) return;
		
		//如果上一个节点是会签节点，则不返回
		strSql = "select * from FLOW_NODE_LIST where FLOW_ID ='" + FLOW_ID + "' and NODE_NEXT = '" + NODE_ID + "'";
		rs = stmt.executeQuery(strSql);
		if(rs != null && rs.next()) nodeRowset = (EFRowSet) DataSetUtils.resultSet2RowSet(rs, nodeRowset);
		
		if(!nodeRowset.getString("NODE_TYPE", "").equals("countersign")) return;
		
		rollbackBM = PO.GetValueByParamName("selRows", "");
		
		if(rollbackBM.trim().length() == 0) {
			throw new Exception("<br>单据没有需要退回的部门信息！");
		}
		bmArray = rollbackBM.split(";");
		//将要删除的部门形成一个索引
		for(int i = 0; i < bmArray.length; i++) {
			rollbackBMMap.put(bmArray[i], bmArray[i]);
		}
		
		//获取分录数据集的KEY
		if(billDataSet.getRowCount() > 0) {
			itemRowSet = billDataSet.getRowSet(0);
			dataSetKeyList = itemRowSet.getDataSetKeyList();
		}
		
		//查询部门
		strSql = " select F_BMBH, F_BMMC from HYBMZD where F_SYZT = '1'";
		rs = stmt.executeQuery(strSql);
		BMDataset = DataSetUtils.resultSet2DataSet(rs, BMDataset);
		
		strSql = "select * from FLOW_NODE_ATTR where FLOW_ID ='" + FLOW_ID + "' and NODE_ID = '" + nodeRowset.getString("NODE_NEXT", "") + "' and ATTR_KEY = 'HQDataSetKey'";
		rs = stmt.executeQuery(strSql);
		//如果定义了要取的数据集KEY
		if(rs != null && rs.next()) {
			strHQDataSetKey = rs.getString("ATTR_VAL");
		} 
		//如果没有定义，则默认取第一个
		else {
			if(dataSetKeyList.size() > 0) strHQDataSetKey = dataSetKeyList.get(0);
		}
		//获取分录数据集
		itemDataSet = itemRowSet.getDataSet(strHQDataSetKey);
	
		
		//获取流程节点
		strSql = "select * from FLOW_TASK_LIST where BIZ_DATE = '" + F_KJQJ + "' and BIZ_DJBH = '" + F_DJBH + "' and "
		       + " FLOW_ID = '" + FLOW_ID + "' and NODE_TAG = '" + PO.GetValueByParamName(FLOW_TASK_LIST._OP_NODE, "") + "' order by OP_ID DESC";
		rs = stmt.executeQuery(strSql);
		flowNodeDS = DataSetUtils.resultSet2DataSet(rs, flowNodeDS);
		flowRowset = flowNodeDS.getRowSet(0);
		
		//更新上一个任务节点的状态
		strSql = "update FLOW_TASK_LIST set RESR_STATUS = 'processed', RESR_OUT_CAUSE = '" + PO.GetValueByParamName(FLOW_TASK_LIST._RESR_OUT_CAUSE, "") + "'"
			   + " where OP_ID = '" + flowRowset.getString("OP_ID", "") + "' and FLOW_ID = '" + FLOW_ID + "'";
		stmt.execute(strSql);
		
		//循环分录数据集
		for(int i = 0; i < itemDataSet.getRowCount(); i++) {
			curTime++;
			itemRowSet = itemDataSet.getRowSet(i);
			//如果部门不用退回，则还原流程节点，继续等待
			if(rollbackBMMap.get(itemRowSet.getString("F_BMBH", "")) == null) {
				flowNodeReducing(stmt, PO, F_KJQJ, F_DJBH, itemRowSet.getString("F_BMBH", ""));
			}
			//如果部门需要退回，则插入上一个节点的代办任务
			else {
				BMRowSet = (EFRowSet) BMDataset.getRowSet(itemRowSet.getString("F_BMBH", ""));
				rollbackCountersignPreNode(stmt, PO, billDataSet, BMRowSet, flowRowset);
			}
		}
	}
	
	/**
	 * 还原节点为等待状态
	 * @param stmt
	 * @param PO
	 * @param F_KJQJ
	 * @param F_DJBH
	 * @param F_BMBH
	 * @throws SQLException
	 */
	private void flowNodeReducing(JStatement stmt, JParamObject PO, String F_KJQJ, String F_DJBH, String F_BMBH) throws SQLException {
		String                           FLOW_ID = PO.GetValueByParamName(FLOW_TASK_LIST._FLOW_ID, "");
		String                            strSql = "";
		ResultSet                             rs = null;
		//获取流程节点
		strSql = "select * from FLOW_TASK_LIST where BIZ_DATE = '" + F_KJQJ + "' and BIZ_DJBH = '" + F_DJBH + "' and "
		       + " FLOW_ID = '" + FLOW_ID + "' and NODE_TAG = '" + PO.GetValueByParamName(FLOW_TASK_LIST._OP_NODE, "") + "'"
		       + " and F_CHAR19 = '" + F_BMBH + "' order by (OP_ID + 0) DESC";
		rs = stmt.executeQuery(strSql);
		if(rs != null && rs.next()) {
			//还原任务节点的状态
			strSql = "update FLOW_TASK_LIST set RESR_STATUS = 'waiting', RESR_OUT_CAUSE = ''"
				   + " where OP_ID = '" + rs.getString("OP_ID") + "' and FLOW_ID = '" + FLOW_ID + "'";
			stmt.execute(strSql);
		}
	}
	
	private void rollbackCountersignPreNode(JStatement stmt, JParamObject PO, EFDataSet billDataSet, EFRowSet BMRowSet, EFRowSet flowRowset) throws Exception {
		EFRowSet                      nodeRowset = EFRowSet.getInstance();
		EFRowSet                  nextNodeRowset = EFRowSet.getInstance();
		String                            strSql = "";
		ResultSet                             rs = null;
		long                             curTime = new Date().getTime();
		String                            F_KJQJ = billDataSet.getRowSet(0).getString(PO.GetValueByParamName(SYS_MODEL._BLFL_KJQJ_COL_, SYS_MDL_VAL.BILL_KJQJ), "");
		String                            F_GUID = billDataSet.getRowSet(0).getString(PO.GetValueByParamName(SYS_MODEL._BILL_GUID_COL_, SYS_MDL_VAL.BILL_GUID), "");
		String                            F_DJBH = billDataSet.getRowSet(0).getString(PO.GetValueByParamName(SYS_MODEL._BILL_BH_COL_, SYS_MDL_VAL.BILL_BH), null);
		String                           FLOW_ID = PO.GetValueByParamName(FLOW_TASK_LIST._FLOW_ID, "");
		String                           NODE_ID = PO.GetValueByParamName(FLOW_TASK_LIST._OP_NODE, "");
		
		//获取提交到节点名称
		strSql = "select * from FLOW_NODE_LIST where FLOW_ID ='" + FLOW_ID + "' and NODE_ID = '" + NODE_ID + "'";
		rs = stmt.executeQuery(strSql);
		if(rs != null && rs.next()) nodeRowset = (EFRowSet) DataSetUtils.resultSet2RowSet(rs, nodeRowset);
		strSql = "select * from FLOW_NODE_LIST where FLOW_ID ='" + FLOW_ID + "' and NODE_NEXT = '" + nodeRowset.getString("NODE_ID", "") + "'";
		rs = stmt.executeQuery(strSql);
		if(rs != null && rs.next()) nextNodeRowset = (EFRowSet) DataSetUtils.resultSet2RowSet(rs, nextNodeRowset);
		
		strSql = "insert into FLOW_TASK_LIST (OP_ID,FLOW_ID,BIZ_DJBH,BIZ_DATE,BIZ_GUID,OP_USER,OP_USER_NAME,OP_TIME,"
			   + "OP_BMBH,OP_NOTE,TASK_STATUS,OP_NODE,NODE_SRC,NODE_SRC_NAME,NODE_TAG,NODE_TAG_NAME,POP_ID,RESR_STATUS,TASK_TO_UNIT,TASK_TO_UNIT_NAME," ;
	 	
		for(int j = 1; j <= 20; j++) {
			if(j < 10) {
				if(PO.GetValueByParamName(FLOW_TASK_LIST._F_CHAR + "0" + j, null) != null) {
					strSql += "F_CHAR0" + j + ",";
				}
				if(PO.GetValueByParamName(FLOW_TASK_LIST._F_DATE + "0" + j, null) != null) {
					strSql += "F_DATE0" + j + ",";
				}
				if(PO.GetValueByParamName(FLOW_TASK_LIST._F_NUM + "0" + j, null) != null) {
					strSql += "F_NUM0" + j + ",";
				}
			} else {
				if(PO.GetValueByParamName(FLOW_TASK_LIST._F_CHAR + j, null) != null) {
					strSql += "F_CHAR" + j + ",";
				}
				if(PO.GetValueByParamName(FLOW_TASK_LIST._F_DATE + j, null) != null) {
					strSql += "F_DATE" + j + ",";
				}
				if(PO.GetValueByParamName(FLOW_TASK_LIST._F_NUM + j, null) != null) {
					strSql += "F_NUM" + j + ",";
				}
			}
		}
	 	strSql += "RESR_IN_CAUSE,RESR_OUT_CAUSE) values ('"
	 	        + curTime + "', '" + PO.GetValueByParamName(FLOW_TASK_LIST._FLOW_ID, "") + "', '"
				+ F_DJBH + "', '" + F_KJQJ + "', '" + F_GUID + "', '" + PO.GetValueByParamName(FLOW_TASK_LIST._OP_USER, "")
				+ "', '" + PO.GetValueByParamName(FLOW_TASK_LIST._OP_USER_NAME, "") + "', '"
				+ curTime + "', '" + PO.GetValueByParamName(FLOW_TASK_LIST._OP_BMBH, "") + "', '" 
				+ PO.GetValueByParamName(FLOW_TASK_LIST._OP_NOTE, "") + "', 'processing', '"
				+ PO.GetValueByParamName(FLOW_TASK_LIST._OP_NODE, "") + "', '" + nodeRowset.getString("NODE_ID", "") + "', '"
				+ nodeRowset.getString("NODE_NAME", "") + "', '" + nextNodeRowset.getString("NODE_ID", "") + "', '" + nextNodeRowset.getString("NODE_NAME", "") 
				+ "', '" + flowRowset.getString("OP_ID", "") + "', '" + PO.GetValueByParamName(FLOW_TASK_LIST._RESR_STATUS, "") 
				+ "','" + BMRowSet.getString("F_BMBH", "") + "','" + BMRowSet.getString("F_BMMC", "") + "',";
	 	for(int j = 1; j <= 20; j++) {
	 		if(j < 10) {
	 			if(PO.GetValueByParamName(FLOW_TASK_LIST._F_CHAR + "0" + j, null) != null) {
	 				strSql += "'" + PO.GetValueByParamName(FLOW_TASK_LIST._F_CHAR + "0" + j, null)  + "',";
	 			} 
	 			if(PO.GetValueByParamName(FLOW_TASK_LIST._F_DATE + "0" + j, null) != null) {
	 				strSql += "'" + PO.GetValueByParamName(FLOW_TASK_LIST._F_DATE + "0" + j, null)  + "',";
	 			}
	 			if(PO.GetValueByParamName(FLOW_TASK_LIST._F_NUM + "0" + j, null) != null) {
	 				strSql += "'" + PO.GetValueByParamName(FLOW_TASK_LIST._F_NUM + "0" + j, null)  + "',";
	 			}
	 		} else {
	 			if(PO.GetValueByParamName(FLOW_TASK_LIST._F_CHAR + j, null) != null) {
	 				strSql += "'" + PO.GetValueByParamName(FLOW_TASK_LIST._F_CHAR + j, null)  + "',";
	 			} 
	 			if(PO.GetValueByParamName(FLOW_TASK_LIST._F_DATE + j, null) != null) {
	 				strSql += "'" + PO.GetValueByParamName(FLOW_TASK_LIST._F_DATE + j, null)  + "',";
	 			}
	 			if(PO.GetValueByParamName(FLOW_TASK_LIST._F_NUM + j, null) != null) {
	 				strSql += "'" + PO.GetValueByParamName(FLOW_TASK_LIST._F_NUM + j, null)  + "',";
	 			}
	 		}
	 	}
	 	strSql += "'" + PO.GetValueByParamName(FLOW_TASK_LIST._RESR_IN_CAUSE, "") + "', '')";
	 	stmt.execute(strSql);
	}
}
